package com.xinjie.www.servlet;

import com.xinjie.www.po.User;
import com.xinjie.www.service.thumb.ThumbServiceImpl;
import com.xinjie.www.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThumbServlet extends HttpServlet {
    ThumbServiceImpl thumbService = new ThumbServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("do".equals(method)){
            this.doThumb(req,resp);
        }
        if ("cancel".equals(method)){
            try {
                this.cancelThumb(req,resp);
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req, resp);
    }

    private void doThumb(HttpServletRequest req, HttpServletResponse resp) {
        int postId = Integer.parseInt(req.getParameter("postId"));
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        User user = (User) o;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(date);
        try {
            boolean b = thumbService.doThumb(postId, user.getUserId(), time);
            if (b) {
                req.getSession().setAttribute("ThumbSuccess", "点赞成功");
                resp.sendRedirect("/UserPage/PostList.jsp");
            } else {
                req.getSession().setAttribute("ThumbLose", "点赞失败");
                resp.sendRedirect("/UserPage/PostList.jsp");
            }
        } catch (SQLException | ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }
    private void cancelThumb(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException, IOException {
        int thumbId = Integer.parseInt(req.getParameter("thumbId"));
        int postId = Integer.parseInt(req.getParameter("postId"));
        boolean b = thumbService.cancelThumb(thumbId, postId);
        if (b){
            req.getSession().setAttribute("CancelThumbSuccess","取消点赞成功");
            resp.sendRedirect("/UserPage/ThumbList.jsp");
        }else {
            req.getSession().setAttribute("CancelThumbLose","取消点赞失败");
            resp.sendRedirect("/UserPage/ThumbList.jsp");
        }
    }
}
